package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.service.ICategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 菜单分类控制层
 *
 * @author panda
 * @since 2022/12/31 1:45
 */
@RestController
@RequestMapping("/category")
@Slf4j
public class CategoryController {

    @Autowired
    private ICategoryService categoryService;

    @PostMapping
    public R<String> saveCategory(@RequestBody Category category) {
        log.info("新增菜品套餐分类为:{}", category);
        categoryService.save(category);
        return R.success("新增成功");
    }

    /**
     * 根据菜品和套餐的sort来进行orderBy排序
     * 降序,花钱多的广告和用餐多的菜品可以展示在最上面
     */
    @GetMapping("/page")
    public R<Page> findByPage(Integer page, Integer pageSize) {
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByDesc(Category::getSort);
        Page<Category> pageCate = new Page<>(page, pageSize);
        categoryService.page(pageCate, queryWrapper);
        return R.success(pageCate);
    }

    /**
     * 因为传递参数是String,否则id的精度会受损
     * 所以使用String来接收参数
     */
    @DeleteMapping
    public R<String> removeById(String id) {
        log.info("----id----:{}", id);
        //categoryService.removeById(id);
        //在删除过程中需要进行有一定的需求进行删除
        //1,如果当前菜品或者套餐在其他表单中正在使用时,是不可以删除当前菜品或者套餐的,
        //必须在当前菜品或者套餐为空时才可以删除
        //select count(*) from category where id = 1111;
        //在service中自定义一个方法,来在库中查询符合条件的数据,此时MP中的方法不够用,
        categoryService.removeCategoryById(id);
        return R.success("删除成功");
    }

    @PutMapping
    public R<String> updeteById(@RequestBody Category category) {
        log.info("category===:{}", category);
        categoryService.updateById(category);
        return R.success("分类修改成功");
    }

    @GetMapping("/list")
    public R<List<Category>> list(Category category) {
        log.info("菜品分类对象:{}", category);
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(category.getType() != null, Category::getType, category.getType());
        queryWrapper.orderByAsc(Category::getSort).orderByDesc(Category::getUpdateTime);
        List<Category> list = categoryService.list(queryWrapper);
        return R.success(list);
    }
}